05. Readers & Writers

Readers and Writers

In this section, you will learn how to read and write character data using the Reader and Writer abstract classes.

ND079 JPND C2 L02 A07 Readers And Writers

Readers / Writers

Readers and Writers are the next level of abstraction built on top of input and output streams. These interfaces read and write text characters.

**We Use Readers/Writers to Work with Text Characters**

We Use Readers/Writers to Work with Text Characters

Reader Example

char[] data = new char[10];
Reader reader =
   Files.newBufferedReader(Path.of("test"), StandardCharsets.UTF_8);
while (reader.read(data) != -1) {
 useData(data);
}
reader.close();

Just like input streams, Readers are usually created with the Files API. But instead of reading bytes, we are reading chars. There's also a StandardCharset, which we'll cover that in more detail in the next video.

Writer Example

Writer writer =
   Files.newBufferedWriter(Path.of("test"),
                           StandardCharsets.UTF_8);
writer.write("hello, world");
writer.close();  // Close the "test" file

The Writer is pretty much what you would expect. This time we are writing encoded Strings of data instead of raw bytes.

If you're just itching to see a coding demo using readers and writers, rest assured there's one on the very next page! I decided to save the demo for the discussion on character encodings.

Readers and Writers are built on top of…

SOLUTION: `InputStream`s and `OutputStream`s

Further Reading